package kattmoy.lucene.text;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class Second {

    public static void main(String[] args) throws IOException, ParseException {
    	
    	//分词器
        Analyzer a = new StandardAnalyzer();
		//从硬盘上获取索引文件
        Directory dir = FSDirectory.open(Paths.get("./index"));
        //读取索引的工具类，常用子类有DirectoryReader
        IndexReader reader = DirectoryReader.open(dir);
        //查询索引的核心类
        IndexSearcher is = new IndexSearcher(reader);
        
        //查询分析器，表示从哪里查用哪个分析器
        QueryParser parser = new QueryParser("contents", a);
        //代表一次查询
        Query query = parser.parse("嘿");
        
        //封装了匹配情况，比如匹配多少个  totalHits 表示匹配的个数
        TopDocs topDocs = is.search(query, 1000);
        System.out.println("总共匹配多少个：" + topDocs.totalHits);
        
        //匹配的数据，里面封装了索引文档的得分和索引ID
        ScoreDoc[] hits = topDocs.scoreDocs;
        
        // 应该与topDocs.totalHits相同
        System.out.println("多少条数据：" + hits.length);
        for (ScoreDoc scoreDoc : hits) {
        	System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        	
            System.out.println("匹配得分：" + scoreDoc.score);
            System.out.println("文档索引ID：" + scoreDoc.doc);
            
            Document document = is.doc(scoreDoc.doc);
            System.out.println(document.get("contents"));
        }
        
        reader.close();
        dir.close();
    }

}